Vue.createApp({
    data() {
        return {
            loginHint: '',
            kaptchaUrl: '/kaptcha',
            kaptcha: '',
            loginInfo: {
                type: 'sender',
                phone: '',
                password: '',
                noLogin: false
            },
            passKaptcha: true
        }
    },
    methods: {
        refreshKaptcha() {
            this.kaptchaUrl = '/kaptcha?' + Math.floor(Math.random() * 100);
        },
        async login() {
            // console.log(this.loginInfo)
            // return;
            if (this.loginInfo.type !== "root") {
                if (!(new RegExp("^\\d{11}$")).test(this.loginInfo.phone)) {
                    this.loginHint = "请正确输入账号(11位数字)";
                    return;
                }
            }

            if (!(new RegExp("[a-zA-Z\\d#*+._-]{6,18}")).test(this.loginInfo.password)) {
                this.loginHint = "请正确输入密码(6-18位, 允许特殊符号#*+._-)";
                return;
            }

            if (!(new RegExp("^\[a-zA-Z0-9]{4}$")).test(this.kaptcha)) {
                this.loginHint = "请正确输入验证码";
                return;
            }

            let pass = false;
            await axios.post("/kaptcha?code=" + this.kaptcha).then((resp) => {
                if (resp.data === true) {
                    pass = true;
                } else {
                    this.loginHint = resp.data;
                }
            });
            if (!pass) {
                this.refreshKaptcha();
                return;
            }

            // console.log(this.loginInfo)

            /*
             * resp.data:
             *      OK - 成功登录
             *      ERROR_x:msg - 出现错误
             *          x = 0 账号密码错误
             *          x = 1 账号已登录
             *          msg: 错误信息
             */
            axios.post("/login", this.loginInfo).then((resp) => {
                // console.log(resp.data)
                // console.log(this.loginInfo)
                if (resp.data === "OK") {
                    this.loginHint = "登录成功，正在跳转...";
                    window.location.href = "/page";
                } else {
                    this.loginHint = resp.data.split(":")[1];
                    this.refreshKaptcha();
                }
            });

        },
    }
}).mount("#login-app");